const webpack = require('webpack');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
// const tsImportPluginFactory = require('ts-import-plugin');
const DynamicPublicPathPlugin = require('./dynamic-publicpath-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const { resolve, plugins, externals, getWebpackOverridesConfig, isSpecialApp } = require('./utils');
const { resolveApp, resolveSeeyonSyf } = require('./resolve');
const { copyEntry } = require('./copy-entry');

const devServerOrigin = 'http://sy-dev.seeyonv8.com';
const proxiesPrefix = ['/i18n', '/dev_-1', '/service', '/static', '/main'];

const host = '0.0.0.0';

const compilationSuccessInfo = [
  `You application is running at http://localhost:${process.env.PORT}`,
];

const headers = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type,Content-Length,Accept,X-Requested-With',
  'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
  'Access-Control-Allow-Credentials': 'true',
};

if (!isSpecialApp) {
  copyEntry();
}

plugins.push(
  new webpack.HotModuleReplacementPlugin(),
  new DynamicPublicPathPlugin(),
  new HtmlWebpackHarddiskPlugin(),
  new FriendlyErrorsWebpackPlugin({
    compilationSuccessInfo: {
      messages: compilationSuccessInfo,
    },
    onErrors: (severity, errors) => {
      if (severity === 'error') {
        console.log('error message:', errors);
      }
    },
  }),
);

let webpackConfig = {
  mode: 'development',
  devtool: 'eval-cheap-module-source-map',
  target: ['web', 'es5'],
  watch: true,
  watchOptions: {
    poll: true,
    ignored: /node_modules/,
  },
  cache: {
    type: 'memory',
  },
  entry: {
    index: [resolveApp('src/entry.tsx')],
  },

  output: {
    path: resolveApp('dist'),
    filename: '[name].js',
    publicPath: `http://localhost:${process.env.PORT}/`,
  },
  plugins,
  externals,
  resolve,
  devServer: {
    host,
    port: process.env.PORT,
    quiet: true,
    hot: true,
    disableHostCheck: true,
    stats: 'errors-only',
    headers,
    historyApiFallback: {
      index: '/index.html',
    },
    proxy: {
      ...proxiesPrefix.reduce((result, curr) => {
        return {
          ...result,
          [curr]: {
            secure: false,
            changeOrigin: true,
            target: devServerOrigin,
          },
        };
      }, {}),
    },
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,
        // include: [/(src)/, /(node_modules)/],
        include: /(src)/,
        exclude: /(node_modules)/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
            },
          },
        ],
      },
      {
        test: /\.(less|css)$/,
        // include: /(src)/,
        // exclude: /(node_modules)/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              modules: {
                auto: true,
                exportLocalsConvention: 'camelCase',
                localIdentName: '[path]-[name]-[local]-[hash:5]',
              },
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                config: resolveSeeyonSyf('scripts/postcss.js'),
              },
            },
          },
          {
            loader: 'less-loader',
            options: {
              lessOptions: {
                javascriptEnabled: true,
              },
            },
          },
        ],
      },
      {
        test: /\.svg$/,
        include: /(src)/,
        exclude: /(node_modules)/,
        use: [
          'babel-loader',
          {
            loader: '@svgr/webpack',
            options: {
              babel: false,
              icon: true,
              titleProp: 'title',
            },
          },
        ],
      },
      {
        test: /\.(graphql|gql)$/,
        include: /(src)/,
        exclude: /(node_modules)/,
        loader: 'graphql-tag/loader',
      },
      {
        test: /\.(jpg|jpeg|gif|png|eot|ttf|woff|woff2)$/,
        include: /(src)/,
        exclude: /(node_modules)/,
        use: {
          loader: 'url-loader',
          options: {
            name: '[name].[hash:8].[ext]',
            limit: 1000,
          },
        },
      },
    ],
  },
};

//读取覆盖默认webpack的配置
const webpackOverride = getWebpackOverridesConfig();

if (typeof webpackOverride === 'function') {
  const resConfig = webpackOverride(webpackConfig, process.env.NODE_ENV);
  if (typeof resConfig === 'object') webpackConfig = resConfig;
}

module.exports = webpackConfig;
